<template>
    <div class="emotion-page">
        <h2 class="title1" style="margin-bottom: 20px;">
            <el-icon :size="25">
                <Setting />
            </el-icon> 权限分配
        </h2>

        <!-- 上半部分：三个容器 -->
        <div class="top-section">
            <!-- 第一个容器：个人信息 -->
            <div class="personal-info-container">
                <div class="avatar">
                    <img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='100' height='100' viewBox='0 0 100 100'%3E%3Ccircle cx='50' cy='50' r='50' fill='%23333'/%3E%3Ccircle cx='50' cy='45' r='15' fill='%23fff'/%3E%3Cpath d='M30 75 Q50 90 70 75' stroke='%23fff' stroke-width='3' fill='none'/%3E%3C/svg%3E"
                        alt="头像" />
                </div>
                <div class="user-name">小美</div>
                <div class="user-birthday">生日：2000-12-23</div>

                <div class="stats-section">
                    <div class="stat-item">
                        <div class="stat-icon">📊</div>
                        <div class="stat-content">
                            <div class="stat-number">4421</div>
                            <div class="stat-label">总检测数</div>
                        </div>
                    </div>

                    <div class="stat-item">
                        <div class="stat-icon">😊</div>
                        <div class="stat-content">
                            <div class="stat-number">积极</div>
                            <div class="stat-label">当前状态</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 第二个容器：情绪热力图 -->
            <div class="emotion-heatmap-container">
                <div class="heatmap-title">情绪热力记录图</div>
                <div class="heatmap-grid">
                    <div v-for="(day, index) in heatmapData" :key="index" class="heatmap-cell-group">
                        <div class="heatmap-cell" :style="{ backgroundColor: getEmotionColor(day.emotion) }"
                            @mouseenter="showTooltip($event, day)" @mouseleave="hideTooltip"></div>
                        <!-- <div class="heatmap-label">{{ day.emotion }}</div> -->
                    </div>
                </div>

                <!-- 映射说明 -->
                <div class="emotion-legend">
                    <div class="legend-items">
                        <div v-for="emotion in emotions" :key="emotion.name" class="legend-item">
                            <div class="legend-color" :style="{ backgroundColor: emotion.color }"></div>
                            <span class="legend-text">{{ emotion.name }}</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 第三个容器：图表分析 -->
            <div class="charts-container">
                <div class="chart-section1">
                    <h4>近五月情绪分析：</h4>
                    <div class="line-chart" ref="lineChartRef" style="width:100%;height:150px;"></div>
                </div>
                <div class="chart-section2" style="height:230px;">
                    <h4>近七天情绪记录：</h4>
                    <div class="radar-chart" ref="radarChartRef" style="width:100%;height:180px;">
                    </div>
                </div>
            </div>
        </div>

        <!-- 下半部分：情绪分析记录容器 -->
        <div class="bottom-section">
            <div class="analysis-records-container">
                <el-card class="box-card" shadow="never" style="width:100%;box-shadow:none;border:none;">
                    <template #header>
                        <div class="table-header">
                            <div class="card-header">
                                <span>情绪分析记录</span>
                            </div>
                        </div>
                    </template>
                    <el-table :data="displayedRecords" border style="width: 100%; margin-top: 20px;"
                        @selection-change="handleSelectionChange">
                        <el-table-column type="selection" width="60"></el-table-column>
                        <el-table-column prop="id" label="记录ID" align="center" width="140"></el-table-column>
                        <el-table-column prop="userId" label="用户ID" align="center" width="140"></el-table-column>
                        <el-table-column prop="name" label="用户名" align="center" width="140"></el-table-column>
                        <el-table-column prop="uploadTime" label="上传时间" align="center"></el-table-column>
                        <el-table-column prop="image" label="上传图片" align="center" width="280">
                            <template #default="scope">
                                <div class="single-line-img">
                                    <span v-if="scope.row.image"
                                        style="max-width:260px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;display:inline-block;">
                                        {{ scope.row.image }}
                                    </span>
                                    <span v-else style="color:#bbb;">无</span>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" align="center" width="350">
                            <template #default="scope">
                                <el-button type="primary" size="middle" @click="viewRecord(scope.row)">查看</el-button>
                                <el-button type="danger" size="middle" @click="deleteRecord(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <!-- <div class="pagination-container" style="margin-top:20px;">
                        <el-pagination background layout="total, prev, pager, next" :total="filteredRecords.length"
                            :page-size="pageSize" :current-page="currentPage" @size-change="handleSizeChange"
                            @current-change="handleCurrentChange" />
                    </div> -->

                    <!-- 分页 -->
                    <div class="pagination-container">
                        <el-pagination background layout="total, sizes, prev, pager, next"
                            :total="filteredRecords.length" :page-size="pageSize" :current-page="currentPage"
                            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                    </div>
                </el-card>


                <!-- 查看弹窗 -->
                <el-dialog v-model="dialogVisible" title="记录信息" width="620px" :close-on-click-modal="false" center>
                    <div class="emo-detail-content">
                        <div class="emo-detail-row">
                            <span class="emo-detail-label">记录ID：</span>
                            <span class="emo-detail-value">{{ currentRecord?.id }}</span>
                        </div>
                        <div class="emo-detail-row">
                            <span class="emo-detail-label">上传图片：</span>
                            <span class="emo-detail-value">
                                <div class="emo-img-box">
                                    <img v-if="currentRecord?.image" :src="currentRecord.image" alt="图片" />
                                    <span v-else style="color:#bbb;">无</span>
                                </div>
                            </span>
                        </div>
                        <div class="emo-detail-row emo-detail-report">
                            <span class="emo-detail-label" style="align-self: flex-start;">情绪分析报告：</span>
                            <span class="emo-detail-value">
                                <div v-if="currentRecord?.emotionReport?.analyze_content" class="emo-rich-content"
                                    v-html="currentRecord.emotionReport.analyze_content"></div>
                                <pre v-else class="emo-json">{{ formattedReport }}</pre>
                            </span>
                        </div>
                        <div class="emo-detail-row">
                            <span class="emo-detail-label" style="align-self: flex-start;">情绪雷达图：</span>
                            <span class="emo-detail-value">
                                <div ref="dialogRadarRef" style="width:320px;height:220px;"></div>
                            </span>
                        </div>
                        <div class="emo-detail-btn">
                            <el-button type="primary" @click="dialogVisible = false">确认/关闭</el-button>
                        </div>
                    </div>
                </el-dialog>
            </div>
        </div>

        <!-- 悬停提示框 -->
        <div v-if="tooltip.show" class="tooltip" :style="{ left: tooltip.x + 'px', top: tooltip.y + 'px' }">
            <div>{{ tooltip.emotion }}</div>
            <div>{{ tooltip.date }}</div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, computed } from 'vue'
import * as echarts from 'echarts'
import { ElMessageBox, ElMessage } from 'element-plus'
import axios from 'axios'
import MarkdownIt from 'markdown-it'

const md = new MarkdownIt()

// 情绪映射
const emotions = [
    { name: '愤怒', color: '#FF8899' },
    { name: '厌恶', color: '#E5EECF' },
    { name: '开心', color: '#FFEAC5' },
    { name: '恐惧', color: '#E5E1E8' },
    { name: '悲伤', color: '#C1D1E2' },
    { name: '惊喜', color: '#FFF2EA' },
    { name: '中性', color: '#EFFBD4' },
    { name: '未检测', color: '#EBEDF0' }
]

// 生成4周的热力图数据（4行7列）
const heatmapData = ref([])

// 提示框数据
const tooltip = reactive({
    show: false,
    x: 0,
    y: 0,
    emotion: '',
    date: ''
})

function generateHeatmapData() {
    const data = []
    const today = new Date()
    for (let i = 27; i >= 0; i--) {
        const date = new Date(today)
        date.setDate(today.getDate() - i)
        const emotion = emotions[Math.floor(Math.random() * emotions.length)].name
        data.push({
            date: formatDate(date),
            emotion: emotion
        })
    }
    heatmapData.value = data
}

function formatDate(date) {
    const year = date.getFullYear().toString().slice(-2)
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    return `${year}${year}-${month}-${day}`
}

function getEmotionColor(emotion) {
    const emotionMap = emotions.find(e => e.name === emotion)
    return emotionMap ? emotionMap.color : '#EBEDF0'
}

function showTooltip(event, day) {
    tooltip.show = true
    tooltip.x = event.pageX + 10
    tooltip.y = event.pageY - 10
    tooltip.emotion = day.emotion
    tooltip.date = day.date
}

function hideTooltip() {
    tooltip.show = false
}

// 折线图数据
const months = ['1月', '2月', '3月', '4月', '5月']
const ratioData = [1.2, 0.8, 1.5, 2.0, 1.7]

// ECharts 折线图
const lineChartRef = ref(null)
let chartInstance = null

// 雷达图数据
const radarChartRef = ref(null)
let radarInstance = null
const radarLabels = ['愤怒', '厌恶', '惊喜', '开心', '恐惧', '悲伤', '中性']
const radarData = [0.8, 0.6, 0.7, 0.9, 0.5, 0.4, 0.7]

onMounted(() => {
    generateHeatmapData()
    // 折线图
    chartInstance = echarts.init(lineChartRef.value)
    chartInstance.setOption({
        grid: {
            top: 10,    // 距离容器顶部20px
            bottom: 20, // 距离容器底部20px
            left: 40,
            right: 20
        },
        tooltip: { trigger: 'axis' },
        xAxis: {
            type: 'category',
            data: months
        },
        yAxis: { type: 'value' },
        series: [{
            name: '积极/消极比值',
            type: 'line',
            data: ratioData,
            smooth: true,
            lineStyle: { color: '#4285f4', width: 3 },
            symbol: 'circle',
            itemStyle: { color: '#4285f4' }
        }]
    })
    // 雷达图
    radarInstance = echarts.init(radarChartRef.value)
    radarInstance.setOption({
        grid: {
            top: -10,    // 距离容器顶部20px
            bottom: 20, // 距离容器底部20px
            left: 40,
            right: 20
        },
        tooltip: {},
        radar: {
            indicator: radarLabels.map(label => ({ name: label, max: 1 })),
            radius: '65%', // 让文字有空间显示
            splitNumber: 5,
            name: {
                textStyle: {
                    fontSize: 12 // 这里设置文字大小
                }
            }
        },
        series: [{
            type: 'radar',
            data: [
                {
                    value: radarData,
                    name: '情绪',
                    areaStyle: { color: 'rgba(255,136,102,0.3)' },
                    lineStyle: { color: '#ff8866', width: 2 },
                    symbol: 'circle',
                    itemStyle: { color: '#ffb48a', borderColor: '#ff8866', borderWidth: 2 }
                }
            ]
        }]
    })
})

onBeforeUnmount(() => {
    chartInstance && chartInstance.dispose()
    radarInstance && radarInstance.dispose()
})

// 表格数据
const records = ref([])

// 获取记录数据
const fetchRecords = async () => {
    // 这里建议用你自己的接口
    // 示例数据
    records.value = [
        { id: 123, name: '小美', image: 'https://via.placeholder.com/60', uploadTime: '2025-3-25' },
        { id: 456, name: '小美', image: 'https://via.placeholder.com/60', uploadTime: '2025-3-25' },
        { id: 789, name: '小美', image: 'https://via.placeholder.com/60', uploadTime: '2025-3-26' },
        { id: 321, name: '小美', image: 'https://via.placeholder.com/60', uploadTime: '2025-3-26' }
    ]
    // 如果有接口，替换为接口请求
    // const response = await axios.get('你的接口地址')
    // records.value = response.data
}

// 分页
const currentPage = ref(1)
const pageSize = ref(5)
const filteredRecords = computed(() => records.value)
const displayedRecords = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    return filteredRecords.value.slice(start, end)
})
const handleCurrentChange = (val) => { currentPage.value = val }
const handleSizeChange = (val) => { pageSize.value = val }

const dialogVisible = ref(false)
const currentRecord = ref(null)
const formattedReport = ref('')

// 查看
const viewRecord = async (row) => {
    currentRecord.value = row
    formattedReport.value = '加载中...'
    dialogVisible.value = true
    // 这里模拟接口
    setTimeout(() => {
        currentRecord.value.emotionReport = {
            analyze_content: '<p>这里是情绪分析报告内容</p>'
        }
        formattedReport.value = JSON.stringify(currentRecord.value.emotionReport, null, 2)
    }, 500)
}

// 删除
const deleteRecord = (row) => {
    ElMessageBox.confirm(`确定要删除记录 ${row.id} 吗？`, '提示', {
        type: 'warning'
    }).then(() => {
        records.value = records.value.filter(r => r.id !== row.id)
        ElMessage.success('删除成功')
    })
}

onMounted(() => {
    fetchRecords()
})
</script>

<style scoped>
.emotion-page {
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
    min-height: 100vh;
}

.title1 {
    display: flex;
    align-items: center;
    gap: 8px;
}

.top-section {
    display: flex;
    gap: 2.5%;
    justify-content: center;
    margin-bottom: 40px;
    flex-wrap: nowrap;
}

/* 第一个容器：个人信息 */
.personal-info-container {
    width: 380px;
    height: 410px;
    background: #fff;
    border-radius: 16px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    padding: 20px 24px 0px 24px;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.avatar {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    overflow: hidden;
    margin-bottom: 20px;
    border: 3px solid #e0e0e0;
}

.avatar img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.user-name {
    font-size: 24px;
    font-weight: 700;
    color: #222;
    margin-bottom: 8px;
}

.user-birthday {
    font-size: 14px;
    color: #888;
    margin-bottom: 32px;
}

.stats-section {
    display: flex;
    gap: 32px;
    width: 100%;
    justify-content: center;
}

.stat-item {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.stat-icon {
    font-size: 28px;
    margin-bottom: 6px;
}

.stat-content {
    flex: 1;
}

.stat-number {
    font-size: 20px;
    font-weight: 700;
    color: #4285f4;
}

.stat-label {
    font-size: 13px;
    color: #888;
}

/* 第二个容器：情绪热力图 */
.emotion-heatmap-container {
    width: 420px;
    height: 410px;
    background: #fff;
    border-radius: 16px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    padding: 20px 24px 0px 24px;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.heatmap-title {
    font-size: 22px;
    font-weight: 700;
    color: #222;
    text-align: center;
    margin-bottom: 24px;
}

.heatmap-grid {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    grid-template-rows: repeat(4, 1fr);
    column-gap: 20px;
    row-gap: 20px;
    margin-bottom: 18px;
}

.heatmap-cell-group {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.heatmap-cell {
    width: 28px;
    height: 28px;
    border-radius: 6px;
    margin-bottom: 4px;
    transition: transform 0.2s;
    cursor: pointer;
    border: 1px solid #f0f0f0;
}

.heatmap-label {
    font-size: 12px;
    color: #888;
    text-align: center;
    margin-top: 2px;
    width: 32px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.emotion-legend {
    margin-top: 20px;
}

.legend-items {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    justify-content: center;
}

.legend-item {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    flex-direction: column;
    gap: 8px;
}

.legend-color {
    width: 16px;
    height: 16px;
    border-radius: 3px;
}

.legend-text {
    font-size: 12px;
    color: #666;
}

/* 第三个容器：图表 */
.charts-container {
    width: 480px;
    height: 430px;
    background: #fff;
    border-radius: 16px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    padding: 0px 24px 0px 12px;
    flex-direction: column;
    align-items: center;
}

.chart-section1 {
    display: flex;
    flex-direction: column;
    height: 230px;
}

.chart-section2 {
    display: flex;
    flex-direction: column;
    height: 160px;
    /* 或更小 */
    margin-top: -30px;
}

.chart-section h4 {
    font-size: 16px;
    color: #222;
}

.line-chart {
    position: relative;
    width: 100%;
}

.chart-legend {
    display: flex;
    gap: 20px;
    justify-content: center;
    margin-top: 10px;
    font-size: 13px;
}

.legend-positive {
    color: #4285f4;
}

.legend-negative {
    color: #ff6b6b;
}

.radar-chart {
    display: flex;
    justify-content: center;
    align-items: flex-start;
    /* 顶部对齐 */
    height: 100%;
}

/* 下半部分容器 */
.bottom-section {
    display: flex;
    justify-content: center;
    margin-bottom: 40px;
    flex-wrap: nowrap;
}

.analysis-records-container {
    width: 1471px;
    min-height: 200px;
    background: white;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    padding: 30px;
    display: flex;
    align-items: flex-start;
    justify-content: center;
    flex-direction: column;
}

.single-line-img {
    display: flex;
    align-items: center;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    height: 40px;
}

.emo-img-box {
    background: #f5f5f5;
    border: 1px solid #eee;
    width: 120px;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.emo-img-box img {
    max-width: 100%;
    max-height: 100%;
}

.emo-detail-content {
    width: 100%;
    padding: 10px 0 0 0;
    display: flex;
    flex-direction: column;
    align-items: stretch;
}

.emo-detail-row {
    display: flex;
    align-items: center;
    margin-bottom: 22px;
    font-size: 15px;
}

.emo-detail-label {
    width: 110px;
    color: #333;
    font-weight: 500;
    text-align: left;
    flex-shrink: 0;
}

.emo-detail-value {
    flex: 1;
    min-height: 28px;
    align-items: center;
    justify-content: flex-start;
}

.emo-img-box {
    background: #f5f5f5;
    border: 1px solid #eee;
    width: 200px;
    height: 100px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.emo-img-box img {
    max-width: 100%;
    max-height: 100%;
}

.emo-detail-report {
    align-items: flex-start;
}

.emo-json {
    font-family: "Consolas", "Menlo", "Monaco", monospace;
    font-size: 13px;
    background: #fafbfc;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    padding: 10px;
    margin: 0;
    width: 420px;
    max-width: 420px;
    min-height: 180px;
    max-height: 260px;
    overflow: auto;
    white-space: pre-wrap;
    word-break: break-all;
}

.emo-rich-content {
    font-size: 14px;
    background: #fafbfc;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    padding: 10px 12px;
    width: 420px;
    min-height: 420px;
    max-height: 260px;
    overflow: auto;
    word-break: break-all;
    line-height: 1.7;
}

.emo-rich-content h3,
.emo-rich-content h4 {
    margin: 8px 0 4px 0;
    font-weight: bold;
}

.emo-rich-content ul,
.emo-rich-content ol {
    margin: 6px 0 6px 18px;
}

.emo-rich-content p {
    margin: 4px 0;
}

.emo-detail-btn {
    display: flex;
    justify-content: center;
    margin-top: 18px;
}
.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: flex-end;
}

/* 提示框 */
.tooltip {
    position: absolute;
    background: rgba(0, 0, 0, 0.8);
    color: white;
    padding: 8px 12px;
    border-radius: 6px;
    font-size: 12px;
    pointer-events: none;
    z-index: 1000;
    line-height: 1.4;
}

/* 响应式设计 */
@media (max-width: 1500px) {
    .top-section {
        flex-direction: column;
        align-items: center;
    }

    .analysis-records-container {
        width: 90%;
        max-width: 800px;
    }
}

@media (max-width: 768px) {

    .personal-info-container,
    .emotion-heatmap-container,
    .charts-container {
        width: 90%;
        max-width: 400px;
    }

    .stats-section {
        flex-direction: column;
        gap: 20px;
    }

    .heatmap-grid {
        max-width: 240px;
    }

    .heatmap-cell {
        width: 28px;
        height: 28px;
    }
}
</style>